<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.searchKey" :placeholder="$t('table.search')" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in searchOptions" :key="item.value" :label="item.label" :value="item.value"/>
      </el-select>
      <el-input :placeholder="$t('couponfiles.name')" v-model="listQuery.searchValue" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <!--<el-select v-model="listQuery.is_available" :placeholder="$t('table.available')" clearable style="width: 90px" class="filter-item">-->
      <!--<el-option v-for="(item, index) in availableOptions" :key="index" :label="item.label" :value="item.value"/>-->
      <!--</el-select>-->
      <el-select
        class="filter-item"
        v-model="listQuery.location_id"
        multiple
        filterable
        allow-create
        default-first-option
        :placeholder="$t('placeholder.select')">
          <el-option-group
            v-for="area in locationOptions"
            :key="area.id"
            :label="area.name"
            :value="area.id">
              <el-option
                v-for="location in area.locations"
                :key="location.id"
                :label="location.name"
                :value="location.id">
              </el-option>
          </el-option-group>
      </el-select>
      <el-select class="filter-item" v-model="listQuery.group_id" multiple :placeholder="$t('placeholder.select')">
        <el-option
          v-for="item in groupOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
      <el-date-picker
                        v-model="listQuery.start_date"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="-"
                        :start-placeholder="$t('placeholder.start_date_from')"
                        :end-placeholder="$t('placeholder.start_date_to')"
                        value-format="yyyy-MM-dd hh:mm:ss">
                    </el-date-picker>
      <el-date-picker
                        v-model="listQuery.end_date"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="-"
                        :start-placeholder="$t('placeholder.expiry_date_from')"
                        :end-placeholder="$t('placeholder.expiry_date_to')"
                        value-format="yyyy-MM-dd hh:mm:ss">
                    </el-date-picker>
    </div>
    <div class="filter-container">  
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleMulDelete">{{ $t('table.batch_delete') }}</el-button>
    </div>

    <template>
      <el-tabs v-model="activeName" type="card" @tab-click="indexRecord">
        <el-tab-pane :label="$t('table.online')" name="first" >
          <el-table
            :data="list"
            border
            fit
            highlight-current-row
            @selection-change="handleSelectionChange"
            style="width: 100%">
            <el-table-column
              type="selection"
              width="35">
            </el-table-column>
            <el-table-column
              :label="$t('table.id')"
              align="center"
              width="50">
              <template slot-scope="scope">
                <span>{{ scope.row.id }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              :label="$t('table.area')"
              align="center"
              width="100px">
              <template slot-scope="scope">
                <span>{{ scope.row.area_name }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('table.available')"
              align="center"
              width="100px">
              <template slot-scope="scope">
                <span>{{ scope.row.available_name }}</span>
              </template>
            </el-table-column>

            <el-table-column
              :show-overflow-tooltip="true"
              :label="$t('couponfiles.name')"
              align="center"
              width="150px">
              <template slot-scope="scope">
                <span>{{ scope.row.name }}</span>
              </template>
            </el-table-column>

            <!--<el-table-column-->
            <!--:show-overflow-tooltip="true"-->
            <!--:label="$t('couponfiles.code')"-->
            <!--align="center"-->
            <!--width="150px">-->
            <!--<template slot-scope="scope">-->
            <!--<span>{{ scope.row.code }}</span>-->
            <!--</template>-->
            <!--</el-table-column>-->

            <el-table-column
              :label="$t('table.start_date')"
              align="center"
              min-width="160px">
              <template slot-scope="scope">
                <span>{{ scope.row.start_date }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('table.end_date')"
              align="center"
              min-width="160px">
              <template slot-scope="scope">
                <span>{{ scope.row.end_date }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('table.actions')"
              align="center"
              width="400">
              <template slot-scope="scope">
                <el-button type="primary" size="small" class="el-icon-edit" @click="handleCouponList(scope.row.id)"> {{ $t('table.detail') }}</el-button>
                <el-button type="primary" size="small" class="el-icon-edit" @click="handleSendCoupon(scope.row.id)"> {{ $t('table.send') }}</el-button>
                <el-button type="primary" size="small" class="el-icon-edit" @click="handleUpdate(scope.row.id)"> {{ $t('table.edit') }}</el-button>
                <el-button type="danger" size="small" class="el-icon-delete" @click="destroyRecord(scope.row)"> {{ $t('table.delete') }}</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
        <el-tab-pane :label="$t('table.offline')" name="second">
          <el-table
            :data="list"
            border
            fit
            highlight-current-row
            @selection-change="handleSelectionChange"
            style="width: 100%">
            <el-table-column
              type="selection"
              width="35">
            </el-table-column>
            <el-table-column
              :label="$t('table.id')"
              align="center"
              width="50">
              <template slot-scope="scope">
                <span>{{ scope.row.id }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              :label="$t('table.area')"
              align="center"
              width="100px">
              <template slot-scope="scope">
                <span>{{ scope.row.area_name }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('table.available')"
              align="center"
              width="100px">
              <template slot-scope="scope">
                <span>{{ scope.row.available_name }}</span>
              </template>
            </el-table-column>

            <el-table-column
              :show-overflow-tooltip="true"
              :label="$t('couponfiles.name')"
              align="center"
              width="150px">
              <template slot-scope="scope">
                <span>{{ scope.row.name }}</span>
              </template>
            </el-table-column>

            <el-table-column
              :show-overflow-tooltip="true"
              :label="$t('couponfiles.code')"
              align="center"
              width="150px">
              <template slot-scope="scope">
                <span>{{ scope.row.code }}</span>
              </template>
            </el-table-column>

            <el-table-column
              :label="$t('table.start_date')"
              align="center"
              min-width="160px">
              <template slot-scope="scope">
                <span>{{ scope.row.start_date }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('table.end_date')"
              align="center"
              min-width="160px">
              <template slot-scope="scope">
                <span>{{ scope.row.end_date }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('table.actions')"
              align="center"
              width="400">
              <template slot-scope="scope">
                <el-button type="primary" size="small" class="el-icon-edit" @click="handleCouponList(scope.row.id)">{{ $t('table.detail') }}</el-button>
                <el-button type="primary" size="small" class="el-icon-edit" @click="handleSendCoupon(scope.row.id)">{{ $t('table.send') }}</el-button>
                <el-button type="primary" size="small" class="el-icon-edit" @click="handleUpdate(scope.row.id)">{{ $t('table.edit') }}</el-button>
                <el-button type="danger" size="small" class="el-icon-delete" @click="destroyRecord(scope.row)">{{ $t('table.delete') }}</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>

      </el-tabs>
    </template>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="indexRecord" />

    <detail ref="detail" :is-edit="isEdit" :edit-id="editId" @indexRecord="indexRecord"/>
    <coupons ref="coupons"/>
    <sendcoupon ref="sendcoupon"/>

  </div>
</template>

<script>
import couponApi from '@/api/coupon/coupon'
import Detail from './components/Detail'
import Coupons from './components/Coupons'
import Sendcoupon from './components/Sendcoupon'

import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import i18n from '@/lang/index'
import { fetchAll as fetchGroupList } from '@/api/group'
import { fetchGroup as fetchLocationGroup } from '@/api/location'

export default {
  name: 'Tag',
  components: { Pagination, Detail, Coupons, Sendcoupon },
  directives: { waves },
  filters: {
  },
  data() {
    return {
      activeName: 'first',
      tableKey: 0,
      list: [],
      groupOptions: [],
      locationOptions: [],
      total: 0,
      listLoading: true,
      listQuery: {
        area: this.$store.getters.area,
        lang: i18n.locale,
        page: 1,
        limit: 20,
        is_available: 2,
        name: '',
        sort: 'desc',
        orderby: 'id',
        searchKey: 'name',
        searchValue: '',
        type: 1,
        location_id: [],
        start_date: [],
        end_date: [],
      },
      coupon_ids: [],
      availableOptions: [
        { 'label': i18n.t('table_element.available.all'), 'value': 2 },
        { 'label': i18n.t('table_element.available.on'), 'value': 1 },
        { 'label': i18n.t('table_element.available.un'), 'value': 0 }
      ],
      editId: 0,
      isEdit: false,
      searchOptions: [
        { value: 'name', label: i18n.t('couponfiles.name') }
      ]
    }
  },
  created() {
    this.indexRecord()
  },
  mounted () {
    this.getLocation()
    this.getGroupList()
  },
  methods: {
    handleFilter() {
      this.listQuery.page = 1
      this.indexRecord()
    },

    handleCreate() {
      this.$refs.detail.handShowDetailDialog(0)
    },

    handleUpdate(id) {
      this.$refs.detail.handShowDetailDialog(id)
    },

    handleCouponList(id) {
      this.$refs.coupons.handShowDetailDialog(id)
    },
    handleSendCoupon(id) {
      this.$refs.sendcoupon.handShowDetailDialog(id)
    },
    indexRecord() {
      this.listLoading = true

      this.coupon_ids = []

      if (this.activeName === 'second') {
        this.listQuery.type = 2
      } else {
        this.listQuery.type = 1
      }

      couponApi.indexRecord(this.listQuery).then(response => {
        const serviceResponse = response.data
        if (serviceResponse.code === 0) {
          this.list = serviceResponse.data.data
          this.total = serviceResponse.data.total
        }
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },

    destroyRecord(row) {
      this.$confirm('Are you sure to delete?', 'Confirm', {
        confirmButtonText: 'confirm',
        cancelButtonText: 'cancel',
        type: 'warning'
      }).then(() => {
        couponApi.destroyRecord(row.id).then(response => {
          const serviceResponse = response.data
          if (serviceResponse.code === 0) {
            this.$message({
              type: 'success',
              message: 'success!'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          } else {
            this.$message({
              type: 'error',
              message: 'error!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel deletion'
        })
      })
    },
    handleMulDelete() {
      this.$confirm('Confirm deletion?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        couponApi.mulDestroyRecord({ coupon_id: this.coupon_ids }).then(response => {
          var data = response.data
          if (data.code == 0) {
            this.$notify({
              title: 'success',
              message: 'Delete successful',
              type: 'success',
              duration: 2000
            })
            this.indexRecord()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel'
        })
      })
    },
    handleSelectionChange(val) {
      val.forEach(element => {
        if (this.coupon_ids.indexOf(element.id) == -1) {
          this.coupon_ids.push(element.id)
        }
      })
    },
    getLocation() {// 地址列表
      let params = {
        area: [this.listQuery.area]
      }
      fetchLocationGroup(params).then((res) => {
        this.locationOptions = res.data.data
      })
    },
    getGroupList() {
      const _this = this
      let params = {
        lang: i18n.locale,
        area: this.listQuery.area,
      }
      fetchGroupList(params).then((res) => {
        this.groupOptions = res.data.data
      })
    },
  }
}
</script>
